<template>
  <div class="p-4">
    <el-card class="mb-4">
      <template #header>
        <div class="flex justify-between items-center">
          <h3 class="font-semibold text-lg">交易流程跟踪</h3>
          <el-button type="primary" @click="handleRefresh">
            <el-icon><Refresh /></el-icon>
            <span>刷新</span>
          </el-button>
        </div>
      </template>
      
      <!-- 搜索筛选区域 -->
      <el-form :inline="true" :model="searchForm" class="mb-4">
        <el-form-item label="交易ID">
          <el-input v-model="searchForm.tradeId" placeholder="请输入交易ID" clearable />
        </el-form-item>
        <el-form-item label="订单号">
          <el-input v-model="searchForm.orderNo" placeholder="请输入订单号" clearable />
        </el-form-item>
        <el-form-item label="交易状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="全部" value="" />
            <el-option v-for="(item, key) in statusMap" :key="key" :label="item" :value="key" />
          </el-select>
        </el-form-item>
        <el-form-item label="交易时间">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
      
      <!-- 交易列表 -->
      <el-table
        :data="tradeList"
        stripe
        border
        fit
        highlight-current-row
        @row-click="handleViewDetail"
        style="cursor: pointer;"
      >
        <el-table-column prop="tradeId" label="交易ID" width="180"></el-table-column>
        <el-table-column prop="orderNo" label="订单号" width="180"></el-table-column>
        <el-table-column prop="amount" label="金额" width="100">
          <template #default="scope">
            ¥{{ scope.row.amount.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="paymentMethod" label="支付方式" width="120"></el-table-column>
        <el-table-column prop="status" label="交易状态" width="120">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ statusMap[scope.row.status] || '未知' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180"></el-table-column>
        <el-table-column label="操作" width="100">
          <template #default="scope">
            <el-button size="small" type="primary" @click="handleViewDetail(scope.row, $event)">
              详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="mt-4 flex justify-center">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 30, 50]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        >
        </el-pagination>
      </div>
    </el-card>

    <!-- 交易详情对话框 -->
    <el-dialog v-model="detailVisible" title="交易详情" :width="800">
      <template #content>
        <el-card class="mb-4">
          <template #header>
            <span>交易基本信息</span>
          </template>
          <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
              <p class="text-sm text-gray-500 mb-1">交易ID</p>
              <p>{{ detailInfo.tradeId }}</p>
            </div>
            <div>
              <p class="text-sm text-gray-500 mb-1">订单号</p>
              <p>{{ detailInfo.orderNo }}</p>
            </div>
            <div>
              <p class="text-sm text-gray-500 mb-1">交易金额</p>
              <p>¥{{ detailInfo.amount.toFixed(2) }}</p>
            </div>
            <div>
              <p class="text-sm text-gray-500 mb-1">手续费</p>
              <p>¥{{ detailInfo.fee.toFixed(2) }}</p>
            </div>
            <div>
              <p class="text-sm text-gray-500 mb-1">支付方式</p>
              <p>{{ detailInfo.paymentMethod }}</p>
            </div>
            <div>
              <p class="text-sm text-gray-500 mb-1">交易状态</p>
              <p>
                <el-tag :type="getStatusType(detailInfo.status)">
                  {{ statusMap[detailInfo.status] || '未知' }}
                </el-tag>
              </p>
            </div>
            <div>
              <p class="text-sm text-gray-500 mb-1">创建时间</p>
              <p>{{ detailInfo.createTime }}</p>
            </div>
            <div>
              <p class="text-sm text-gray-500 mb-1">完成时间</p>
              <p>{{ detailInfo.completeTime || '-' }}</p>
            </div>
          </div>
        </el-card>

        <el-card class="mb-4">
          <template #header>
            <span>买家信息</span>
          </template>
          <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
              <p class="text-sm text-gray-500 mb-1">用户名</p>
              <p>{{ detailInfo.buyer.username }}</p>
            </div>
            <div>
              <p class="text-sm text-gray-500 mb-1">手机号</p>
              <p>{{ detailInfo.buyer.phone }}</p>
            </div>
            <div>
              <p class="text-sm text-gray-500 mb-1">邮箱</p>
              <p>{{ detailInfo.buyer.email }}</p>
            </div>
          </div>
        </el-card>

        <el-card class="mb-4">
          <template #header>
            <span>交易流程</span>
          </template>
          <el-timeline>
            <el-timeline-item
              v-for="(step, index) in detailInfo.steps"
              :key="index"
              :timestamp="step.time"
              :type="index <= currentStepIndex ? (step.success ? 'success' : 'danger') : 'info'"
              :color="index <= currentStepIndex ? (step.success ? '#10b981' : '#ef4444') : '#9ca3af'"
            >
              <el-card :shadow="index <= currentStepIndex ? 'hover' : 'never'">
                <div class="flex justify-between items-center mb-2">
                  <span class="font-medium">{{ step.name }}</span>
                  <el-tag 
                    v-if="index <= currentStepIndex" 
                    :type="step.success ? 'success' : 'danger'"
                  >
                    {{ step.success ? '成功' : '失败' }}
                  </el-tag>
                </div>
                <p class="text-gray-600">{{ step.description || '无描述' }}</p>
                <div class="mt-2 text-sm text-gray-500" v-if="step.operator">
                  操作人: {{ step.operator }}
                </div>
              </el-card>
            </el-timeline-item>
          </el-timeline>
        </el-card>

        <el-card v-if="detailInfo.refundInfo">
          <template #header>
            <span>退款信息</span>
          </template>
          <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
              <p class="text-sm text-gray-500 mb-1">退款金额</p>
              <p>¥{{ detailInfo.refundInfo.amount.toFixed(2) }}</p>
            </div>
            <div>
              <p class="text-sm text-gray-500 mb-1">退款原因</p>
              <p>{{ detailInfo.refundInfo.reason }}</p>
            </div>
            <div>
              <p class="text-sm text-gray-500 mb-1">退款状态</p>
              <p>{{ detailInfo.refundInfo.status }}</p>
            </div>
            <div>
              <p class="text-sm text-gray-500 mb-1">退款时间</p>
              <p>{{ detailInfo.refundInfo.time || '-' }}</p>
            </div>
          </div>
        </el-card>
      </template>
      <template #footer>
        <el-button @click="detailVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { Refresh } from '@element-plus/icons-vue'

// 交易状态映射
const statusMap = {
  pending: '待支付',
  paid: '已支付',
  shipping: '发货中',
  delivered: '已送达',
  completed: '已完成',
  refunding: '退款中',
  refunded: '已退款',
  failed: '交易失败',
  cancelled: '已取消'
}

// 获取状态标签类型
const getStatusType = (status) => {
  switch (status) {
    case 'pending':
      return 'info'
    case 'paid':
    case 'shipping':
      return 'warning'
    case 'delivered':
    case 'completed':
      return 'success'
    case 'refunding':
    case 'refunded':
      return 'primary'
    case 'failed':
    case 'cancelled':
      return 'danger'
    default:
      return 'info'
  }
}

// 模拟交易数据
const mockTrades = [
  {
    tradeId: 'TRADE20230901001',
    orderNo: 'ORD20230901001',
    amount: 299.99,
    fee: 0.00,
    paymentMethod: '支付宝',
    status: 'completed',
    createTime: '2023-09-01 10:30:00',
    completeTime: '2023-09-03 15:45:00'
  },
  {
    tradeId: 'TRADE20230902002',
    orderNo: 'ORD20230902002',
    amount: 599.00,
    fee: 5.99,
    paymentMethod: '微信支付',
    status: 'delivered',
    createTime: '2023-09-02 14:15:00',
    completeTime: null
  },
  {
    tradeId: 'TRADE20230903003',
    orderNo: 'ORD20230903003',
    amount: 1299.00,
    fee: 12.99,
    paymentMethod: '银联支付',
    status: 'shipping',
    createTime: '2023-09-03 09:45:00',
    completeTime: null
  },
  {
    tradeId: 'TRADE20230904004',
    orderNo: 'ORD20230904004',
    amount: 79.90,
    fee: 0.00,
    paymentMethod: '支付宝',
    status: 'paid',
    createTime: '2023-09-04 16:20:00',
    completeTime: null
  },
  {
    tradeId: 'TRADE20230905005',
    orderNo: 'ORD20230905005',
    amount: 1599.00,
    fee: 15.99,
    paymentMethod: '微信支付',
    status: 'refunded',
    createTime: '2023-09-05 11:30:00',
    completeTime: '2023-09-07 10:15:00'
  }
]

// 模拟交易详情数据
const mockTradeDetail = {
  tradeId: 'TRADE20230901001',
  orderNo: 'ORD20230901001',
  amount: 299.99,
  fee: 0.00,
  paymentMethod: '支付宝',
  status: 'completed',
  createTime: '2023-09-01 10:30:00',
  completeTime: '2023-09-03 15:45:00',
  buyer: {
    username: 'testuser',
    phone: '13800138000',
    email: 'test@example.com'
  },
  steps: [
    {
      name: '交易创建',
      time: '2023-09-01 10:30:00',
      description: '用户创建订单并发起支付',
      operator: '系统',
      success: true
    },
    {
      name: '支付处理',
      time: '2023-09-01 10:32:15',
      description: '支付系统处理中',
      operator: '支付宝',
      success: true
    },
    {
      name: '支付成功',
      time: '2023-09-01 10:35:40',
      description: '用户支付成功，订单已确认',
      operator: '系统',
      success: true
    },
    {
      name: '准备商品',
      time: '2023-09-01 14:20:30',
      description: '商家已确认订单，正在准备商品',
      operator: '商家A',
      success: true
    },
    {
      name: '商品发货',
      time: '2023-09-02 09:15:00',
      description: '商品已发货，快递单号：SF1234567890',
      operator: '商家A',
      success: true
    },
    {
      name: '运输中',
      time: '2023-09-02 15:30:45',
      description: '快递已揽收，正在运输中',
      operator: '顺丰速运',
      success: true
    },
    {
      name: '已送达',
      time: '2023-09-03 10:20:10',
      description: '快递已送达，正在派送',
      operator: '顺丰速运',
      success: true
    },
    {
      name: '交易完成',
      time: '2023-09-03 15:45:00',
      description: '用户已签收，交易完成',
      operator: '系统',
      success: true
    }
  ],
  refundInfo: null
}

// 状态管理
const tradeList = ref([])
const detailVisible = ref(false)
const detailInfo = ref({})
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const localTrades = ref([...mockTrades])

// 搜索表单
const searchForm = reactive({
  tradeId: '',
  orderNo: '',
  status: '',
  dateRange: []
})

// 当前步骤索引（用于时间线显示）
const currentStepIndex = computed(() => {
  const statusIndexMap = {
    pending: 0,
    paid: 2,
    shipping: 4,
    delivered: 6,
    completed: 7,
    refunding: 5,
    refunded: 7,
    failed: 1,
    cancelled: 0
  }
  
  return statusIndexMap[detailInfo.value.status] || 0
})

// 获取交易列表
const fetchTradeList = () => {
  // 应用搜索筛选
  let filtered = [...localTrades.value]
  
  if (searchForm.tradeId) {
    filtered = filtered.filter(item => 
      item.tradeId.includes(searchForm.tradeId)
    )
  }
  
  if (searchForm.orderNo) {
    filtered = filtered.filter(item => 
      item.orderNo.includes(searchForm.orderNo)
    )
  }
  
  if (searchForm.status) {
    filtered = filtered.filter(item => item.status === searchForm.status)
  }
  
  if (searchForm.dateRange && searchForm.dateRange.length === 2) {
    const [startDate, endDate] = searchForm.dateRange
    filtered = filtered.filter(item => {
      const tradeDate = new Date(item.createTime).getTime()
      const start = new Date(startDate).getTime()
      const end = new Date(endDate).getTime() + 24 * 60 * 60 * 1000 // 包含结束日期当天
      
      return tradeDate >= start && tradeDate <= end
    })
  }
  
  // 模拟分页
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  tradeList.value = filtered.slice(start, end)
  total.value = filtered.length
}

// 搜索交易
const handleSearch = () => {
  currentPage.value = 1
  fetchTradeList()
}

// 重置搜索
const resetSearch = () => {
  searchForm.tradeId = ''
  searchForm.orderNo = ''
  searchForm.status = ''
  searchForm.dateRange = []
  currentPage.value = 1
  fetchTradeList()
}

// 刷新列表
const handleRefresh = () => {
  fetchTradeList()
  ElMessage.success('刷新成功')
}

// 查看详情
const handleViewDetail = (row, event) => {
  if (event) {
    event.stopPropagation() // 阻止行点击事件冒泡
  }
  
  // 模拟获取详情数据
  detailInfo.value = JSON.parse(JSON.stringify(mockTradeDetail))
  detailInfo.value.tradeId = row.tradeId
  detailInfo.value.orderNo = row.orderNo
  detailInfo.value.amount = row.amount
  detailInfo.value.fee = row.fee
  detailInfo.value.paymentMethod = row.paymentMethod
  detailInfo.value.status = row.status
  detailInfo.value.createTime = row.createTime
  detailInfo.value.completeTime = row.completeTime
  
  // 如果是退款状态，添加退款信息
  if (row.status === 'refunding' || row.status === 'refunded') {
    detailInfo.value.refundInfo = {
      amount: row.amount,
      reason: '用户申请退款',
      status: row.status === 'refunding' ? '处理中' : '已完成',
      time: row.status === 'refunded' ? '2023-09-07 10:15:00' : null
    }
  } else {
    detailInfo.value.refundInfo = null
  }
  
  detailVisible.value = true
}

// 分页相关
const handleSizeChange = (newSize) => {
  pageSize.value = newSize
  fetchTradeList()
}

const handleCurrentChange = (newPage) => {
  currentPage.value = newPage
  fetchTradeList()
}

// 生命周期钩子
onMounted(() => {
  fetchTradeList()
})
</script>

<style scoped>
/* 自定义样式 */
</style>